package io.github.jieblog.juc.day7;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by jie on 2017/6/16.
 * ConcurrentLinkedQueue 高并发环境中性能最好的代码
 */
public class ConcurrentLinkedQueueTest {
    public static void main(String[] args) {
        Queue<Integer> queue = new ConcurrentLinkedQueue();

        for (int i = 0; i < 10; i++) {
            queue.add(i);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executorService.submit(new Task1(queue));
            executorService.submit(new Task2(queue));
        }
        System.out.println(queue.size());
    }


}

class Task1 implements Callable<Integer> {
    Queue<Integer> queue;

    public Task1(Queue queue) {
        this.queue = queue;
    }

    @Override
    public Integer call() throws Exception {
        Integer integer = queue.poll();
        System.out.println(integer);
        return null;
    }
}

class Task2 implements Callable<Integer> {
    Queue<Integer> queue;

    public Task2(Queue queue) {
        this.queue = queue;
    }

    @Override
    public Integer call() throws Exception {
        Random random = new Random();
        queue.add(random.nextInt());
        return null;
    }
}